package com.meiyuetao.myt.job;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import lab.s2jh.core.pagination.GroupPropertyFilter;
import lab.s2jh.core.pagination.PropertyFilter;
import lab.s2jh.core.pagination.PropertyFilter.MatchType;
import lab.s2jh.core.util.DateUtils;
import lab.s2jh.ctx.DynamicConfigService;
import lab.s2jh.ctx.FreemarkerService;
import lab.s2jh.ctx.MailService;
import lab.s2jh.schedule.BaseQuartzJobBean;

import org.apache.commons.collections.CollectionUtils;
import org.joda.time.LocalDateTime;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.meiyuetao.myt.sale.entity.BoxOrder;
import com.meiyuetao.myt.sale.entity.BoxOrder.BoxOrderStatusEnum;
import com.meiyuetao.myt.sale.entity.BoxOrderDetail;
import com.meiyuetao.myt.sale.entity.BoxOrderDetail.BoxOrderDetailStatusEnum;
import com.meiyuetao.myt.sale.entity.BoxOrderDetail.CommoditiesTypeEnum;
import com.meiyuetao.myt.sale.service.BoxOrderDetailService;
import com.meiyuetao.myt.sale.service.BoxOrderService;

public class IybHourlyJob extends BaseQuartzJobBean {
    private final static Logger logger = LoggerFactory.getLogger(IybHourlyJob.class);

    @Override
    protected void executeInternalBiz(JobExecutionContext context) {
        logger.debug("IybHourlyJob executing...");
        StringBuilder sb = new StringBuilder();

        BoxOrderService boxOrderService = this.getSpringBean(BoxOrderService.class);
        BoxOrderDetailService boxOrderDetailService = this.getSpringBean(BoxOrderDetailService.class);

        FreemarkerService freemarkerService = this.getSpringBean(FreemarkerService.class);
        DynamicConfigService dynamicConfigService = this.getSpringBean(DynamicConfigService.class);

        Map<String, List<Map<String, String>>> resultMap = new HashMap<String, List<Map<String, String>>>();
        Map<String, String> resultLittleMap;
        // 自动取消48小时未付款订单
        GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
        groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "orderStatus", BoxOrderStatusEnum.S10O));
        groupPropertyFilter.append(new PropertyFilter(MatchType.LT, "orderTime", new LocalDateTime().minusDays(2).toDate()));
        // filters.add(new PropertyFilter(MatchType.NULL, "actualPayedAmount",
        // true));
        List<BoxOrder> boxOrders = boxOrderService.findByFilters(groupPropertyFilter);
        List<Map<String, String>> resultList = new ArrayList<Map<String, String>>();
        if (CollectionUtils.isNotEmpty(boxOrders)) {
            for (BoxOrder boxOrder : boxOrders) {
                resultLittleMap = new LinkedHashMap<String, String>();
                resultLittleMap.put("订单号：", boxOrder.getOrderSeq());
                resultLittleMap.put("订单名", boxOrder.getTitle() == null ? "" : boxOrder.getTitle());
                resultLittleMap.put("下单时间：", boxOrder.getOrderTime() == null ? "" : DateUtils.formatTime(boxOrder.getOrderTime()));
                resultLittleMap.put("已付总金额：", boxOrder.getActualPayedAmount() == null ? "" : String.valueOf(boxOrder.getActualPayedAmount()));
                resultLittleMap.put("状态：", boxOrder.getOrderStatus() == null ? "" : boxOrder.getOrderStatus().name());
                resultLittleMap.put("客户：", boxOrder.getCustomerProfile() == null ? "" : boxOrder.getCustomerProfile().getDisplay());
                resultList.add(resultLittleMap);
                sb.append("自动取消48小时未付款订单：" + boxOrder.getOrderSeq() + "<br>\n");
                boxOrder.buildLastOperationSummary("自动取消48小时未付款");
                boxOrderService.cancelOrder(boxOrder);
            }
        }
        if (resultList.size() > 0) {
            resultMap.put("自动取消48小时未付款订单：", resultList);
        }
        // 服务类商品生成消费码
        groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
        groupPropertyFilter.append(new PropertyFilter(MatchType.IN, "orderDetailStatus", new BoxOrderDetailStatusEnum[] { BoxOrderDetailStatusEnum.S20PYD,
                BoxOrderDetailStatusEnum.S25PYD, BoxOrderDetailStatusEnum.S30C, BoxOrderDetailStatusEnum.S35C, BoxOrderDetailStatusEnum.S40DP }));
        groupPropertyFilter.append(new PropertyFilter(MatchType.NE, "commoditiesType", CommoditiesTypeEnum.GOODS));
        List<BoxOrderDetail> boxOrderDetails = boxOrderDetailService.findByFilters(groupPropertyFilter);
        resultList = new ArrayList<Map<String, String>>();
        if (CollectionUtils.isNotEmpty(boxOrders)) {
            for (BoxOrderDetail boxOrderDetail : boxOrderDetails) {
                boxOrderDetailService.genPurchaseCode(boxOrderDetail);
            }
        }

        String emailHTML = null;
        // 发送通知邮件
        if (resultMap.size() > 0) {
            String emailToList = dynamicConfigService.getString("cfg.boxOrder.status.email.list", "");
            // String emailToList = configParameter.getExtValue();
            Map<String, Object> dataMap = new HashMap<String, Object>();
            Map<String, List<Map<String, String>>> resultMapHourly = new HashMap<String, List<Map<String, String>>>();
            dataMap.put("resultMap", resultMapHourly);
            dataMap.put("resultMapHourly", resultMap);
            dataMap.put("fireTimeHourly", DateUtils.formatTime(context.getFireTime()));
            emailHTML = freemarkerService.processTemplateByFileName("IYB_ORDER_DAILY_NOTIFY", dataMap);
            if (emailToList != null) {
                MailService mailService = this.getSpringBean(MailService.class);
                mailService.sendHtmlMail("订单状态通知邮件", emailHTML, false, emailToList);
            }
        }

        context.setResult(emailHTML);
    }
}
